package service

import (
	"time"

	"gitee.com/liumou_site/go-network-monitoring/types"
	"github.com/shirou/gopsutil/v3/cpu"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/host"
	"github.com/shirou/gopsutil/v3/load"
	"github.com/shirou/gopsutil/v3/mem"
)

// SystemService 系统统计服务
type SystemService struct {
	startTime time.Time
}

// NewSystemService 创建系统统计服务实例
func NewSystemService(startTime time.Time) *SystemService {
	return &SystemService{
		startTime: startTime,
	}
}

// GetSystemStats 获取详细的系统统计信息
func (ss *SystemService) GetSystemStats() (types.SystemStats, error) {
	stats := types.SystemStats{
		UpdateTime: time.Now().Format("2006-01-02 15:04:05"),
		Runtime:    time.Since(ss.startTime).Round(time.Second).String(),
	}

	// 获取CPU使用率
	if cpuPercent, err := cpu.Percent(time.Second, false); err == nil && len(cpuPercent) > 0 {
		stats.CPUUsage = cpuPercent[0]
	}

	// 获取内存使用率
	if memInfo, err := mem.VirtualMemory(); err == nil {
		stats.MemoryUsage = memInfo.UsedPercent
	}

	// 获取磁盘使用率（根分区）
	if diskInfo, err := disk.Usage("/"); err == nil {
		stats.DiskUsage = diskInfo.UsedPercent
	}

	// 获取系统负载
	if loadInfo, err := load.Avg(); err == nil {
		stats.LoadAvg1 = loadInfo.Load1
		stats.LoadAvg5 = loadInfo.Load5
		stats.LoadAvg15 = loadInfo.Load15
	}

	// 获取系统运行时间
	if hostInfo, err := host.Info(); err == nil {
		uptime := time.Duration(hostInfo.Uptime) * time.Second
		stats.Uptime = uptime.String()
	}

	return stats, nil
}

// GetSystemStatsSimple 获取简化的系统统计信息（用于兼容现有代码）
func (ss *SystemService) GetSystemStatsSimple() map[string]interface{} {
	result := make(map[string]interface{})

	// 获取CPU使用率
	if cpuPercent, err := cpu.Percent(time.Second, false); err == nil && len(cpuPercent) > 0 {
		result["cpu_usage"] = cpuPercent[0]
	} else {
		result["cpu_usage"] = 0.0
	}

	// 获取内存使用率
	if memInfo, err := mem.VirtualMemory(); err == nil {
		result["memory_usage"] = memInfo.UsedPercent
		result["memory_total"] = memInfo.Total
		result["memory_used"] = memInfo.Used
		result["memory_available"] = memInfo.Available
	} else {
		result["memory_usage"] = 0.0
		result["memory_total"] = 0
		result["memory_used"] = 0
		result["memory_available"] = 0
	}

	// 获取磁盘使用率
	if diskInfo, err := disk.Usage("/"); err == nil {
		result["disk_usage"] = diskInfo.UsedPercent
		result["disk_total"] = diskInfo.Total
		result["disk_used"] = diskInfo.Used
		result["disk_free"] = diskInfo.Free
	} else {
		result["disk_usage"] = 0.0
		result["disk_total"] = 0
		result["disk_used"] = 0
		result["disk_free"] = 0
	}

	// 获取系统负载
	if loadInfo, err := load.Avg(); err == nil {
		result["load_avg_1"] = loadInfo.Load1
		result["load_avg_5"] = loadInfo.Load5
		result["load_avg_15"] = loadInfo.Load15
	} else {
		result["load_avg_1"] = 0.0
		result["load_avg_5"] = 0.0
		result["load_avg_15"] = 0.0
	}

	// 获取系统运行时间
	if hostInfo, err := host.Info(); err == nil {
		result["uptime"] = hostInfo.Uptime
		result["uptime_string"] = time.Duration(hostInfo.Uptime * uint64(time.Second)).String()
	} else {
		result["uptime"] = 0
		result["uptime_string"] = "unknown"
	}

	// 添加程序运行时间
	result["runtime"] = time.Since(ss.startTime).Round(time.Second).String()
	result["update_time"] = time.Now().Format("2006-01-02 15:04:05")

	return result
}

// GetVersionInfo 获取版本信息
func (ss *SystemService) GetVersionInfo(version, appName, description string) types.VersionInfo {
	return types.VersionInfo{
		Version:     version,
		AppName:     appName,
		Description: description,
	}
}

// BuildHtmlData 构建HTML模板数据
func (ss *SystemService) BuildHtmlData(hostname, interfaceName, ipv4, version, appName string) types.HtmlData {
	return types.HtmlData{
		Hostname:      hostname,
		InterfaceName: interfaceName,
		Ipv4:          ipv4,
		Version:       version,
		AppName:       appName,
		Runtime:       time.Since(ss.startTime).Round(time.Second).String(),
	}
}